package com.webzavod.model;

import com.webzavod.json.OrderJSON;
import com.webzavod.model.User;
import org.hibernate.annotations.Index;

import javax.persistence.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: v.tsapaev
 * Date: 25.05.12
 * Time: 18:44
 * To change this template use File | Settings | File Templates.
 */
@Entity
@Table(name="customer_order")
public class Order {

    @Id
    @Column(name = "order_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer orderId;

    /**
     *  Book - is book, Integer - books count
     */
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name="book_order",
            joinColumns=@JoinColumn(name="book_order_id"))
    @Column(name="count_books")
    @MapKeyJoinColumn(name="book", referencedColumnName="book_id")
    private Map<Book, Integer> bookMap = new HashMap<Book, Integer>();

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User owner;

    public Order(){}

    public Order(OrderJSON orderJSON){
        this();
        orderId = orderJSON.getOrderId();
        owner = orderJSON.getOwner();
        bookMap = new HashMap<Book, Integer>();
        for (Book book: orderJSON.getBookList()){
            Integer countBook = 1;
            if (bookMap.containsKey(book)){
                countBook = bookMap.get(book) + 1;
                bookMap.remove(book);
            }
            bookMap.put(book, countBook);
        }
    }

    public Integer getOrderId() {
        return orderId;
    }

    public void setOrderId(Integer orderId) {
        this.orderId = orderId;
    }

    public Map<Book, Integer> getBookMap() {
        return bookMap;
    }

    public void setBookMap(Map<Book, Integer> bookMap) {
        this.bookMap = bookMap;
    }

    public User getOwner() {
        return owner;
    }

    public void setOwner(User owner) {
        this.owner = owner;
    }

    @Override
    public String toString() {
        return "Order{" +
                "orderId=" + orderId +
                ", bookMap=" + bookMap +
                ", owner=" + owner +
                '}';
    }
}
